package org.soretro.portfolio.view.background
{
	import flash.display.Sprite;
	
	import mx.events.ResizeEvent;
	
	import org.osmf.events.TimeEvent;
	import org.robotlegs.mvcs.Mediator;
	import org.soretro.portfolio.controller.events.LoadingBarsEvent;
	import org.soretro.portfolio.model.MainNavigationModel;
	
	public class LoadingBarsMediator extends Mediator
	{
		[Inject]
		public var view:LoadingBarsView;
		
		[Inject]
		public var model:MainNavigationModel;
		
		public var maskArea:Sprite;
		public var borderFlicker:BorderFlicker;

		override public function onRegister():void
		{
			borderFlicker = new BorderFlicker();
			view.flickerContainer.addChild(borderFlicker);
			
			drawMask();
			
			view.flickerContainer.addEventListener( ResizeEvent.RESIZE, onResize );
			
			eventMap.mapListener(eventDispatcher, LoadingBarsEvent.LOADING, loadingBarsHandler);
			eventMap.mapListener(eventDispatcher, LoadingBarsEvent.LOAD_END, endLoadingBarsHandler);
			
			onResize();
//			addViewListener(LoadingBarsEvent.LOADING, loadingBarsHandler);
//			addViewListener(CopyrightStripEvent.DEFAULT, copyrightStripHandler1);
//			addContextListener(CopyrightStripEvent.LOADING, copyrightStripHandler2);
		}
		
		protected function onResize(event:ResizeEvent = null):void
		{
			borderFlicker.width = view.flickerContainer.width;
			borderFlicker.height = view.flickerContainer.height;
			
			drawMask();
			if ( !maskArea ) return;
			maskArea.width = borderFlicker.width;
			maskArea.height = borderFlicker.height;
		}
		
		private function endLoadingBarsHandler( event:LoadingBarsEvent ):void
		{
			model.endLoading();
			borderFlicker.stopLoading();
		}
		
		private function loadingBarsHandler( event:LoadingBarsEvent ):void
		{
//			if ( borderFlicker.myBitmap.visible ) {
//				trace("Stop LOADING NOW...");
//				borderFlicker.stopLoading();
//				dispatch( new CopyrightStripEvent( CopyrightStripEvent.DEFAULT, "" )  );
//			} else {
				model.startLoading();
				trace("Start LOADING NOW...");
				borderFlicker.startLoading();
//				dispatch( new CopyrightStripEvent( CopyrightStripEvent.LOADING, "LOAD: Screen will update soon..." )  );
				
//			}
		}
		
		private function drawMask():void
		{
			maskArea = new Sprite();
			
			maskArea.graphics.beginFill(0xFFFFFF);
			
			maskArea.graphics.drawRect(0,0,view.flickerContainer.width,30);
			maskArea.graphics.drawRect(0,0,30,view.flickerContainer.height);
			
			maskArea.graphics.drawRect(view.flickerContainer.width-30,0,30,view.flickerContainer.height);
			maskArea.graphics.drawRect(0,view.flickerContainer.height-30,view.flickerContainer.width,30);
			
			maskArea.graphics.endFill();
			borderFlicker.mask = maskArea;
		}
		
		private function copyrightStripHandler1( event:CopyrightStripEvent ):void
		{
			trace("copyrightStripHandler1");
		}
		
		private function copyrightStripHandler2( event:CopyrightStripEvent ):void
		{
			trace("copyrightStripHandler2");
		}
	}
}